import React from 'react';
import { Row } from 'antd';

export default () => {
  return Comp => {
    return class GetLabel extends React.Component {
      constructor(props) {
        super(props);
        this.ref = React.createRef();
      }

      state = {
        labelWidth: 0,
      }

      componentDidUpdate(prevProps, prevState) {
        const { getData } = this.props;
        const margin = getData('labelMargin');
        if (this.ref.current) {
          const currentWidth = Math.ceil(this.ref.current.getBoundingClientRect().width + Number(margin || 0));
          if (prevState.labelWidth !== currentWidth) {
            // eslint-disable-next-line react/no-did-update-set-state
            this.setState({
              labelWidth: currentWidth,
            });
          }
        }
      }

      render() {
        const { getData } = this.props;
        const { labelWidth } = this.state;
        let label = getData('label') || '';
        const align = getData('labelAlign');
        const margin = getData('labelMargin');
        const required = getData('required');
        if (label || required) {
          label = `${label}:`;
          return (
            <Row type="flex" align={align}>
              <span style={{ marginRight: margin }} ref={this.ref}>{required ? <span style={{ fontWeight: 600, color: 'red', marginRight: 4, fontSize: '16px' }}>*</span> : null}{label}</span>
              {labelWidth ? <Comp {...this.props} labelWidth={labelWidth} /> : <Comp {...this.props} />}
            </Row>
          );
        }
        return <Comp {...this.props} />;
      };
    };
  };
};
